package users

import (
	"github.com/jinzhu/gorm"
	"time"
)

type UserCredentials struct {
	ID        int64      `gorm:"column:id;primary_key" json:"id"`
	UserId    string     `gorm:"column:user_id" json:"userId"`
	AccessKey string     `gorm:"column:access_key" json:"accessKey"`
	SecretKey string     `gorm:"column:secret_key" json:"secretKey"`
	Status    int32      `gorm:"column:status" json:"status"`
	User      User       `gorm:"foreignKey:UserId" json:"user,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `sql:"index" json:"deleted_at,omitempty"`
}

type UserCredentialReq struct {
	ID        int64  `json:"id"`
	UserId    string `json:"userId"`
	AccessKey string `json:"accessKey"`
	SecretKey string `json:"secretKey"`
	Status    int32  `json:"status"`
}

func NewUserCredential() *UserCredentials {
	return &UserCredentials{}
}

func (u *UserCredentials) TableName() string {
	return "user_credentials"
}

func (u *UserCredentials) Create(db *gorm.DB) error {
	return db.Create(&u).Error
}

func (u *UserCredentials) DeleteByID(db *gorm.DB, ids interface{}) error {
	return db.Table(u.TableName()).Where("id in (?)", ids).Delete(UserCredentials{}).Error
}

func (u *UserCredentials) GetByAccessKey(db *gorm.DB, accessKey string) error {
	return db.Preload("User").Where("access_key = ?", accessKey).Where("status = ?", 1).First(&u).Error
}

func (u *UserCredentials) GetListByUserId(db *gorm.DB, userId string) (*[]UserCredentials, error) {
	user_crendentials := []UserCredentials{}
	err := db.Where("user_id = ?", userId).
		Where("status = ?", 1).
		Find(&user_crendentials).
		Error
	if err != nil {
		return nil, err
	}
	return &user_crendentials, nil
}

func (u *UserCredentials) UpdateCredential(db *gorm.DB, id int64, conditions map[string]interface{}) error {
	return db.Table(u.TableName()).Where("id = ?", id).Update(conditions).Error
}
